package com.multiple.sources.core.util;

import java.util.Map;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;


public class SpringContextUtil {
	private static ApplicationContext applicationContext;  
	  
    //获取上下文  
    public static ApplicationContext getApplicationContext() {  
        return applicationContext;  
    }  
  
    //设置上下文  
    public static void setApplicationContext(ApplicationContext applicationContext) {  
        SpringContextUtil.applicationContext = applicationContext;  
    }  
  
    //通过名字获取上下文中的bean  
    public static Object getBean(String name){  
        return applicationContext.getBean(name);  
    }  
      
    //通过类型获取上下文中的bean  
    public static Object getBean(Class<?> requiredType){  
        return applicationContext.getBean(requiredType);  
    }  
    
    
    public static void addSource(	Map<Object, Object>  targetDataSources){
    	DefaultListableBeanFactory defaultListableBeanFactory=(DefaultListableBeanFactory) getApplicationContext().getAutowireCapableBeanFactory();
    	
		GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
		MutablePropertyValues mpv = beanDefinition.getPropertyValues();
		mpv.addPropertyValue("targetDataSources", targetDataSources);
		//mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
		defaultListableBeanFactory.registerBeanDefinition("targetDataSources", beanDefinition);
		
		
    }
}
